package com.ccnf.service.impl;

import com.ccnf.core.utils.SystemClock;
import com.ccnf.model.entity.ScheduleTask;
import com.ccnf.model.mapper.ScheduleTaskMapper;
import com.ccnf.service.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Value("${spring.application.name}")
    private String appName;
    @Autowired
    private ScheduleTaskMapper scheduleTaskMapper;

    @Override
    @Transactional
    public boolean beforeScheduleTask(long timeId) {
        ScheduleTask scheduleTask = scheduleTaskMapper.selectByTimeId(timeId);
        String taskDesc = appName + "定时任务";
        if (scheduleTask == null) {
            log.error(appName + "初始化信息未设置");
            scheduleTask = new ScheduleTask();
            scheduleTask.setTimeId(timeId);
            scheduleTask.setTaskDesc(taskDesc);
            scheduleTask.setIsRun(0);
            try {
                scheduleTaskMapper.insert(scheduleTask);
                return true;
            } catch (Exception e) {
                log.error("插入定时任务失败", e.getMessage());
                return false;
            }
        }
        if (scheduleTask.getIsRun() == 1) {
            log.error(taskDesc + "已经执行完毕 --> " + timeId);
            return false;
        }
        Integer count = scheduleTaskMapper.updateByTimeIdAndIsRun(timeId);
        if (count == 0) {
            log.error(taskDesc + "已经正在运行中 --> " + timeId);
            return false;
        }
        return true;
    }

    @Override
    public void afterScheduleTask(long timeId, long startTime) {
        ScheduleTask scheduleTask = new ScheduleTask();
        scheduleTask.setTimeId(timeId);
        scheduleTask.setIsSuccess(1);
        scheduleTask.setRuntime((int) (SystemClock.milli() - startTime));
        scheduleTaskMapper.updateById(scheduleTask);
        ScheduleTask insertScheduleTask = new ScheduleTask();
        insertScheduleTask.setTimeId(timeId + 86400);
        insertScheduleTask.setTaskDesc(appName + "定时任务执行");
        scheduleTaskMapper.insert(insertScheduleTask);
    }
}